<template>
  <div>
    <div id="chart"></div>
  </div>

</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'RiskStackedBarChart',
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart);
  },
  methods: {
    initChart() {
      const chartDom = document.getElementById('chart');
      this.chart = echarts.init(chartDom);

      // 数据定义，每个对象代表一个二级指标
      // secondary：二级指标相对权重
      // tertiary：各三级指标的相对权重（堆叠后总和等于二级指标的权重）
      const categories = [
        { name: '核心供应商', secondary: 0.417, tertiary: [
            { name: '关键原材料/配件进口依赖度', value: 0.383 },
            { name: '关键设备进口依赖度', value: 0.273 },
            { name: '关键技术服务进口依赖度', value: 0.172 },
            { name: '产品国产化率', value: 0.172 }
          ]},
        { name: '孤源/单一供应商', secondary: 0.205, tertiary: [
            { name: '关键原材料/配件进口依赖度', value: 0.175 },
            { name: '关键设备进口依赖度', value: 0.270 },
            { name: '关键技术服务进口依赖度', value: 0.190 },
            { name: '产品国产化率', value: 0.206 },
            { name: '孤源/单一供应商数量占比', value: 0.159 }
          ]},
        { name: '整体结构', secondary: 0.378, tertiary: [
            { name: '供应链整体稳定性', value: 0.379 },
            { name: '供应链整体脆弱性', value: 0.319 },
            { name: '供应链整体抗毁性', value: 0.302 }
          ]},
        { name: '技术封锁', secondary: 0.453, tertiary: [
            { name: '关键设备持有国集中度', value: 0.243 },
            { name: '关键设备持有国敌对程度', value: 0.259 },
            { name: '关键技术服务持有国集中度', value: 0.270 },
            { name: '关键技术服务持有国敌对程度', value: 0.228 }
          ]},
        { name: '政治冲突', secondary: 0.396, tertiary: [
            { name: '关键设备供应国政局不稳定程度', value: 0.339 },
            { name: '关键技术服务提供国政局不稳定程度', value: 0.315 },
            { name: '关键原材料/配件供应国政府不稳定程度', value: 0.345 }
          ]},
        { name: '区域热点', secondary: 0.091, tertiary: [
            { name: '是否发生恐怖袭击、局部战争等导致的供应中断', value: 1.000 }
          ]},
        { name: '自然灾害', secondary: 0.060, tertiary: [
            { name: '是否发生洪水、地震等导致的供应中断', value: 1.000 }
          ]},
        { name: '生产经营', secondary: 0.489, tertiary: [
            { name: '民营生产企业总数占比', value: 0.200 },
            { name: '核心供应商民营企业可替代性', value: 0.400 },
            { name: '关键原材料/配件产能不足数量', value: 0.230 },
            { name: '存在交付延迟的产品占全部产品的比重', value: 0.170 }
          ]},
        { name: '质量安全', secondary: 0.130, tertiary: [
            { name: '产品合格率', value: 0.583 },
            { name: '关键设备故障率', value: 0.417 }
          ]},
        { name: '科技人才', secondary: 0.380, tertiary: [
            { name: '关键技术研发能力', value: 0.314 },
            { name: '关键技术与国外先进技术对比先进程度', value: 0.219 },
            { name: '保障政策完善度', value: 0.162 },
            { name: '复合型人才短缺度', value: 0.305 }
          ]}
      ];

      // x轴显示二级指标名称
      const xAxisData = categories.map(cat => cat.name);
      // 计算各组中最多有多少个三级指标（用于构造堆叠系列）
      const maxTertiary = Math.max(...categories.map(cat => cat.tertiary.length));

      // 构造堆叠系列，每个系列代表各组中第 i 个三级指标
      const series = [];
      for (let i = 0; i < maxTertiary; i++) {
        const seriesData = [];
        for (let j = 0; j < categories.length; j++) {
          const cat = categories[j];
          if (cat.tertiary[i]) {
            // 计算该段值 = 二级指标权重 × 三级指标相对权重
            const segValue = cat.secondary * cat.tertiary[i].value;
            seriesData.push({
              value: segValue,
              // 保存三级指标名称，用于 tooltip 显示
              thirdName: cat.tertiary[i].name
            });
          } else {
            seriesData.push(0);
          }
        }
        series.push({
          name: '',
          type: 'bar',
          stack: 'total',
          label: { show: false },
          // 添加动画延迟，增加动态效果
          animationDelay: function (idx) {
            return idx * 100;
          },
          itemStyle: {
            borderRadius: [5, 5, 0, 0],
            shadowBlur: 4,
            shadowColor: 'rgba(0,0,0,0.3)',
            shadowOffsetX: 2,
            shadowOffsetY: 2
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0,0,0,0.5)'
            }
          },
          data: seriesData
        });
      }

      const option = {
        title: {
          text: '二级指标及其三级指标构成',
          left: 'center',
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          backgroundColor: 'rgba(50,50,50,0.7)',
          borderColor: '#777',
          borderWidth: 1,
          formatter: function(params) {
            // params 为当前 x 轴某个分类下所有堆叠系列的数据
            const idx = params[0].dataIndex;
            const catData = categories[idx];
            let tip = `<strong>${catData.name}</strong><br/>二级指标权重：${catData.secondary}<br/>`;
            tip += '三级指标：<br/>';
            params.forEach(item => {
              if (item.value && item.data && item.data.thirdName) {
                tip += `${item.data.thirdName}: ${item.value.toFixed(3)}<br/>`;
              }
            });
            return tip;
          }
        },
        legend: { show: false },
        grid: {
          left: '10%',
          right: '10%',
          bottom: '15%',
          top: '20%'
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisLabel: {
            rotate: 30,
            textStyle: {
              fontSize: 12,
              color: '#333'
            }
          },
          axisTick: { alignWithLabel: true }
        },
        yAxis: {
          type: 'value',
          name: '相对权重',
          min: 0,
          max: 1,
          axisLabel: {
            color: '#666',
            fontSize: 12
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#ddd'
            }
          }
        },
        series: series,
        // 全局动画设置
        animationDuration: 1200,
        animationEasing: 'elasticOut'
      };

      this.chart.setOption(option);
    },
    resizeChart() {
      if (this.chart) {
        this.chart.resize();
      }
    }
  }
}
</script>

<style scoped>
#chart {
  width: 100%;
  height: 650px;
}
</style>
